package example.util;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 局部锁实现。
 * @author 王振宇
 */
@Slf4j
public class LockerUtil {
    /**
     * 实现锁。
     */
    private static ReentrantLock reentrantLock = new ReentrantLock();
    /**
     * 锁池。
     */
    private static volatile ConcurrentHashMap<String, RateLimiter> lockerHashMap = new ConcurrentHashMap<>();

    /**
     * 获取锁
     */
    public boolean lock(String key) {
        try{
            reentrantLock.lock();
            log.info("1");
            RateLimiter rateLimiter = null;
            if (lockerHashMap.containsKey(key)) {
                rateLimiter = lockerHashMap.get(key);
            } else {
                rateLimiter = RateLimiter.create(0.1);
                lockerHashMap.put(key, rateLimiter);
                System.out.println("123");
            }
            boolean rateBoolean = false;
            do {
                rateBoolean = rateLimiter.tryAcquire();
                if(!rateBoolean) {
                    try {
                        log.info(key + "key限流中，等待获取令牌。");
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        log.error(e.getMessage());
                    }
                }
            } while (!rateBoolean);
            log.info("2");
        } finally {
            reentrantLock.unlock();
        }
        return true;
    }
}
